package com.rtx.wms.std.asn.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.common.EdiBeanUtils;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.asn.bean.ApiReceipt;
import com.rtx.wms.std.asn.bean.ApiReceiptdetail;
import com.rtx.wms.std.asn.mapper.ApiReceiptMapper;
import com.rtx.wms.std.asn.mapper.ApiReceiptdetailMapper;
import com.rtx.wms.std.asn.mapper.dymapper.DyApiReceiptMapper;
import com.rtx.wms.std.asn.mapper.dymapper.DyApiReceiptdetailMapper;
import com.rtx.wms.std.asn.mapper.dymapper.DyReceiptMapper;
import com.rtx.wms.std.asn.service.ApiReceiptService;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.so.bean.ApiOrderdetail;
import com.rtx.wms.std.so.bean.ApiOrders;

import cn.hutool.core.util.IdUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcw
 * @since 2023-04-20
 */
@Service
public class ApiReceiptServiceImpl implements ApiReceiptService {

    @Autowired
    private ApiReceiptdetailMapper apiReceiptdetailMapper;
    
    @Autowired
    ApiReceiptMapper baseMapper;
    
    @Autowired
    DyApiReceiptMapper dyApiReceiptMapper;
    
    @Autowired
    DyApiReceiptdetailMapper dyApiReceiptdetailMapper;

    @DataSourceAnnotation
    @Override
    public void addApiReceipt(String whseid, ApiReceipt apiReceipt,EdiInnerRequestDTO dto) {
        String batchid = IdUtil.getSnowflakeNextIdStr();
        
        //是否使用 动态加载字段拼接sql
        boolean activeConfig = false;
        //获取edi 配置
        ApiMappingInfoBo config =  Optional.ofNullable(dto.getConfig()).orElse(new ApiMappingInfoBo()) ;
        //获取生效的目标apiid，就是当前需要被调用的restapi
        Long targetid = config.getTargetApi().getId();
        //获取启动或者被被更新时候动态创建的实体类
        Map<String,Class> map = ClassHolder.apiconfigClassMap.get(targetid+"");
        //假如动态创建的类存在则 通过调用通过反射获取bean对象属性拼接sql的方法
        if(map != null) {
        	activeConfig = true;
        }
        
        for(ApiReceiptdetail apiReceiptdetail : apiReceipt.getDetails()){
        	apiReceiptdetail.setBatchid(batchid);
        	apiReceiptdetail.setExternreceiptkey(apiReceipt.getExternreceiptkey());
        	
        	if(activeConfig) {
        		dyApiReceiptdetailMapper.rtxconfigColumnsSave(apiReceiptdetail);
        	}else {
        		apiReceiptdetailMapper.insert(apiReceiptdetail);
        	}
        }
        apiReceipt.setBatchid(batchid);
        apiReceipt.setEdiflag("P");
        
    	if(activeConfig) {
    		dyApiReceiptdetailMapper.rtxconfigColumnsSave(apiReceipt);
    	}else {
    		baseMapper.insert(apiReceipt);
    	}
//        baseMapper.insert(apiReceipt);
    }

    @DataSourceAnnotation
    @Override
    public List<ApiReceipt> selectApiReceiptByWrapper(String whseid, Wrapper<ApiReceipt> wrapper,ApiMappingInfoBo bo) {
        List<ApiReceipt> receiptList = convertToConfigApiReceipt(bo,(QueryWrapper<ApiReceipt>) wrapper);
        for(ApiReceipt o : receiptList){
            QueryWrapper<ApiReceiptdetail> detailQuery = Wrappers.query();
            detailQuery.eq("batchid",o.getBatchid());
            List<ApiReceiptdetail> details = convertToConfigApiReceiptdetail(bo,detailQuery);
            o.setDetails(details);
        }
        return receiptList;
    }
    
    //获取有新增字段的对象
    private List<ApiReceipt> convertToConfigApiReceipt(ApiMappingInfoBo bo,QueryWrapper<ApiReceipt> qw){
    	List<ApiReceipt> head = new ArrayList<>();
    	try {
    		String apiid =  bo.getTargetApi().getId()+"";
    		Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

    		if(map != null && map.get("main") != null) {
    			Class headclass = map.get("main");
    			qw.select(EdiBeanUtils.getCoulmns(headclass));
    			List<Map<String, Object>> oriData = baseMapper.selectMaps(qw);
    			for(Map<String, Object> dataMap:oriData) {
    				ApiReceipt o =(ApiReceipt) EdiBeanUtils.copyFields(dataMap, headclass);
    				head.add(o);
    			}
    		}else {
    			head = baseMapper.selectList(qw);
    		}
    	} catch (Exception e) {
    		head = baseMapper.selectList(qw);
    	}

    	return head;
    }
    
    //获取有新增字段的对象
    private List<ApiReceiptdetail> convertToConfigApiReceiptdetail(ApiMappingInfoBo bo,QueryWrapper<ApiReceiptdetail> qw){
    	List<ApiReceiptdetail> head = new ArrayList<>();
    	try {
    		String apiid =  bo.getTargetApi().getId()+"";
    		Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

    		if(map != null && map.get("sub") != null) {
    			Class detailclass = map.get("sub");
    			qw.select(EdiBeanUtils.getCoulmns(detailclass));
    			List<Map<String, Object>> oriData = apiReceiptdetailMapper.selectMaps(qw);
    			for(Map<String, Object> dataMap:oriData) {
    				ApiReceiptdetail o =(ApiReceiptdetail) EdiBeanUtils.copyFields(dataMap, detailclass);
    				head.add(o);
    			}
    		}else {
    			head = apiReceiptdetailMapper.selectList(qw);
    		}
    	} catch (Exception e) {
    		head = apiReceiptdetailMapper.selectList(qw);
    	}

    	return head;
    }

    @DataSourceAnnotation
    @Override
    public void updateByWrapper(String whseid,LambdaUpdateWrapper<ApiReceipt> update) {
        baseMapper.update(null,update);
    }

    @DataSourceAnnotation
	@Override
	public List<ApiReceipt> selectApiReceiptByWrapperNoDetail(String whseid, Wrapper<ApiReceipt> wrapper) {
		return baseMapper.selectList(wrapper);
	}
}
